package com.itmck.config;


import com.alibaba.fastjson.JSONObject;
import com.itmck.dao.UserMapper;
import com.itmck.dto.ApiResultResponse;
import com.itmck.util.RequestUtil;
import com.itmck.util.SpringContextUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


public class JWTAuthcFilter extends AccessControlFilter{


    private static Logger log = LoggerFactory.getLogger(JWTAuthcFilter.class);

    private boolean isDisabled;

    private ApplicationContext applicationContext;


    public JWTAuthcFilter(boolean isDisabled) {
        this.isDisabled = isDisabled;
    }



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isDisabled) {
            log.info("Shiro Authentication is disabled, hence  can access api directly.");
            //返回true代表当前请求放行
            return true;
        } else {
            log.info("Shiro Authentication is enabled, to continue to execute onAccessDenied method");
        }
        //返回false，代码会走到onAccessDenied方法，进行处理
        return false;
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        // 登录状态判断
        log.info("onAccessDenied......");
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated()) {
            return true;
        }

        //从header或URL参数中查找token
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = RequestUtil.getRequestValueByKey(req, "token");
        if (!StringUtils.isEmpty(authorization)) {
            UserMapper bean = SpringContextUtils.getBean(UserMapper.class);
            log.info("{}",bean);
            CustomToken token = new CustomToken("mck", "123");
            try {
                getSubject(request, response).login(token);
                return true;
            } catch (Exception e) {
                log.error("认证失败:" + e.getMessage());
            }
        }
        PrintWriter out = null;
        try {
            // 这里就很简单了，向Response中写入Json响应数据，需要声明ContentType及编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JSONObject.toJSONString(ApiResultResponse.error("登录失败","11111")));
        } catch (IOException exception) {
            exception.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return false;
    }
}